<template>
  <div class="box hide-scroller-bar" @scroll="loadImg($event)" ref="pageRef">
    <div style="padding: 30px; padding-bottom: 0px">
      <a-breadcrumb separator=">" class="breadcrumb">
        <a-breadcrumb-item @click="$router.push({ name: 'PaintModel' })">
          <span class="pointer">首页</span>
        </a-breadcrumb-item>
        <a-breadcrumb-item>
          <span class="pointer">分类页</span>
        </a-breadcrumb-item>
      </a-breadcrumb>
      <a-row
        v-for="(item, index) in tagList"
        :key="item.id"
        class="classify"
        :wrap="false"
      >
        <a-row>
          <a-col class="title classify-title">{{ item.name }}</a-col>
        </a-row>
        <a-row style="display: flex; flex: 1">
          <a-col
            class="classify-tag"
            :class="tags.checked ? 'tag-bg' : ''"
            v-for="tags in item.tags"
            :key="tags.id"
            @click="tagClick(index, tags)"
            >{{ tags.name }}</a-col
          >
        </a-row>
      </a-row>
    </div>

    <!-- <a-row>
      <a-col> <a-tag closable @close="closClick">二级分类</a-tag></a-col>
    </a-row> -->
    <div style="padding-left: 30px">
      <a-divider />
    </div>
    <a-row style="padding-left: 30px">
      <a-space :size="25">
        <a-col
          class="pointer"
          v-for="item in sortText"
          :key="item.key"
          :class="item.key == sortIndex ? 'sort-title' : 'text-color'"
          @click="sortTextClick(item.key)"
          >{{ item.title }}</a-col
        >
      </a-space>
    </a-row>
    <a-spin :spinning="false" :delay="600">
      <div
        class="discover"
        v-masonry
        transition-duration="0.1s"
        item-selector=".discoveImg"
        id="discover-width"
        fit-width="true"
      >
        <div
          v-for="item in caseList"
          :key="item.id"
          class="discoveImg"
          v-masonry-tile
          :style="{
            width: imageWidth + 'px',
          }"
        >
          <div class="discoveTxt" @click.stop="makeTheSameModelClick(item)">
            <a-row class="bottom-text mask-right">
              <div class="icon-bg">
                <VerticalAlignBottomOutlined
                  v-if="item.downloadLoading"
                  @click.stop="downloadClick(item)"
                />
                <LoadingOutlined v-else />
              </div>
              <div class="icon-bg" @click.stop="collectClick(item)">
                <HeartFilled
                  v-if="item.collect && $store.getters.isLogin"
                  style="color: red"
                />
                <HeartOutlined v-else />
              </div>
            </a-row>
            <div class="text-box">
              {{ item.title }}
            </div>
            <div class="make-box" @click.stop="makeTheSameModelClick(item)">
              创作
            </div>
          </div>
          <img
            v-if="item.images"
            v-lazy="
              item.images[0].webp ? item.images[0].webp : item.images[0].uri
            "
            :style="{
              width: imageWidth + 'px',
              height:
                imageWidth * (item.images[0].height / item.images[0].width) +
                'px',
            }"
          />
        </div>
      </div>
    </a-spin>
    <!-- 登录弹框 -->
    <LoginModal
      :visible="loginVisible"
      @onClose="loginVisible = false"
      @loginCallback="loginCallback"
    />

    <!-- 回到顶部 -->
    <div class="back-to-top" v-show="headerFixed" @click.stop="backToTop">
      <ArrowUpOutlined />
    </div>
  </div>
</template>

<script>
import {
  defineComponent,
  ref,
  reactive,
  toRefs,
  computed,
  watch,
  toRaw,
  onDeactivated,
  onMounted,
  nextTick,
} from "vue";
import { useRoute, useRouter } from "vue-router";
import { message } from "ant-design-vue";
import {
  VerticalAlignBottomOutlined,
  HeartOutlined,
  LoadingOutlined,
  ArrowUpOutlined,
  HeartFilled,
} from "@ant-design/icons-vue";
import request from "../../common/utils/request";
import utils from "../../common/utils/utils.js";
import axios from "axios";
import store from "../../store/index.js";
import moment from "moment";
import Masonry from "masonry-layout";
import defaultSetting from "../../common/utils/defaultSetting";

export default defineComponent({
  name: "classify",
  components: {
    VerticalAlignBottomOutlined,
    HeartOutlined,
    LoadingOutlined,
    ArrowUpOutlined,
    HeartFilled,
  },
  setup() {
    const route = useRoute();
    const router = useRouter();

    const state = reactive({
      count: 0,
      spinning: false,
      sortIndex: 1,
      sortText: [
        {
          title: "综合排序",
          key: 1,
        },
        {
          title: "最新上传",
          key: 2,
        },
        {
          title: "最多下载",
          key: 3,
        },
      ],
      tagList: [],
      tagId: [],
      caseList: [],
      page: 1,
      pageSize: 20,
      isData: true,
      createDesc: undefined,
      downDesc: undefined,
      downloadLoading: false,

      loginVisible: false,

      headerFixed: false,
      pageRef: null,

      imageWidth: 0,
    });

    const loadImg = (event) => {
      let el = event.target;
      if (Math.ceil(el.scrollTop + el.clientHeight) >= el.scrollHeight) {
        if (state.isData) {
          state.page++;
          getCaseList(state.tagId.join(",") || undefined);
        }
      }

      if (el.scrollTop >= 500) {
        state.headerFixed = true;
      } else {
        state.headerFixed = false;
      }
    };
    const createDesc = undefined;
    const downDesc = undefined;
    const sortTextClick = (key) => {
      if (state.sortIndex == key) {
        return;
      }
      state.sortIndex = key;
      state.page = 1;
      state.caseList = [];
      if (key == 1) {
        state.createDesc = undefined;
        state.downDesc = undefined;
      }
      if (key == 2) {
        state.createDesc = 1;
        state.downDesc = undefined;
      }
      if (key == 3) {
        state.downDesc = 1;
        state.createDesc = undefined;
      }
      getCaseList(state.tagId.join(",") || undefined);
    };

    // 制作同款
    const makeTheSameModelClick = (item) => {
      utils.setStorage("caseInfo", JSON.stringify(item));
      let url = `${
        utils.isEnv()
          ? `http://localhost:${location.port}`
          : defaultSetting.requestDomain
      }`;
      let link = url + `/#/paintModel/detail?id=${item.id}`;
      window.open(link);
    };

    const downloadClick = (item) => {
      if (item.images.length > 1) {
        // // 设置请求URL和参数
        const url = "/api/work_ai/user/image/case/download";
        const params = {
          caseId: item.id,
          org_id: store.getters.orgId,
        };
        item.downloadLoading = true;
        // 发送GET请求
        axios
          .get(url, {
            params,
            responseType: "blob", // 告诉axios要响应二进制数据类型
          })
          .then((response) => {
            // 创建Blob对象
            console.log(response, "responseresponse");
            const blob = new Blob([response.data], { type: "application/zip" });
            // 创建URL对象，并模拟点击链接进行下载
            const downloadUrl = URL.createObjectURL(blob);
            const link = document.createElement("a");
            link.href = downloadUrl;
            link.download =
              store.getters.orgId +
              item.id +
              moment(new Date()).format("YYYYMMDD"); // 下载文件名
            link.click();
          })
          .catch((error) => {
            setTimeout(() => {
              item.downloadLoading = false;
            }, 0);
          })
          .finally(() => {
            setTimeout(() => {
              item.downloadLoading = false;
            }, 0);
          });
      } else {
        var image = new Image();
        // 解决跨域 Canvas 污染问题
        // crossorigin 是HTML5中新增的<img>标签属性
        //anonymous:如果使用这个值的话就会在请求中的header中的带上origin属性，但请求不会带上cookie和其他的一些认证信息。
        //use-credentials:这个同时会在跨域请求中带上cookie和其他的一些认证信息。在使用这两个值时都需要server端在response的header中带上Access-Control-Allow-Credentials属性。可以通过server的配置文件来开启这个属性：server开启Access-Control-Allow-Credentials
        image.setAttribute("crossOrigin", "anonymous");
        image.onload = function () {
          var canvas = document.createElement("canvas");
          canvas.width = image.width;
          canvas.height = image.height;
          var context = canvas.getContext("2d");
          context.drawImage(image, 0, 0, image.width, image.height);
          var url = canvas.toDataURL("image/png");
          // 生成一个a元素
          var a = document.createElement("a");
          // 创建一个单击事件
          var event = new MouseEvent("click");
          // 将a的download属性设置为我们想要下载的图片名称，若name不存在则使用‘下载图片名称’作为默认名称
          a.download = item.images[0].origin_uri.substring(
            item.images[0].origin_uri.lastIndexOf("/") + 1
          );
          // 将生成的URL设置为a.href属性
          a.href = url;

          // 触发a的单击事件
          a.dispatchEvent(event);
        };
        image.src = item.images[0].uri;
      }
    };
    const collectClick = (item) => {
      utils.checkLogin().then((isLogin) => {
        if (!isLogin) {
          state.loginVisible = true;
          return;
        }
        if (item.collect) {
          console.log(item);
          request
            .del("/work_ai", "/user/image/case/collect/delete", {
              case_id: item.id,
              id: item.collect_id || item.collection.id,
            })
            .then((res) => {
              message.success("取消收藏成功！");
              item.collect = 0;
            });
        } else {
          request
            .post("/work_ai", "/user/image/case/collect/save", {
              case_id: item.id,
            })
            .then((res) => {
              message.success("收藏成功！");
              item.collect_id = res.id;
              item.collect = 1;
            });
        }
      });
    };
    const loginCallback = () => {
      state.loginVisible = false;
      router.go(0);
    };

    // 标签点击
    const tagClick = (index, tags) => {
      if (tags.checked) return;
      state.page = 1;
      state.caseList = [];
      state.tagList[index].tags.map((v) => {
        if (v.id == tags.id) {
          v.checked = true;
        } else {
          v.checked = false;
        }
      });

      let params = [];
      state.tagList.map((v) => {
        v.tags.map((item) => {
          if (item.checked && typeof item.id == "number") {
            params.push(item.id);
          }
        });
      });
      if (params.length > 0) {
        getCaseList(params.join(","));
      } else {
        getCaseList(undefined);
      }
      // if (state.tagId.includes(id)) {
      //   let index = state.tagId.findIndex((item) => item == tags.id);
      //   state.tagId.splice(index, 1);
      //   getCaseList(state.tagId.join(",") || undefined);
      //   return;
      // }
      // state.tagId.push(id);
      // getCaseList(state.tagId.join(",") || undefined);
    };

    const getCaseList = (tagId) => {
      state.spinning = true;
      request
        .get("/work_ai", "/user/image/case/list", {
          page: state.page,
          pageSize: state.pageSize,
          tagId,
          createDesc: state.createDesc,
          downDesc: state.downDesc,
        })
        .then((res) => {
          if (res.result) {
            if (res.result.to == res.result.total || !res.result.to) {
              state.isData = false;
            } else {
              state.isData = true;
            }
            res.result.data.forEach((item) => {
              item.downloadLoading = true;
              item.collect = item.collection ? 1 : 0;
            });
            // state.caseList = state.caseList.concat(res.result.data);
            state.caseList = [...state.caseList, ...res.result.data];
            nextTick(() => {
              document.getElementById("discover-width").style.marginLeft =
                "30px";
            });
            state.spinning = false;
          }
        });
    };

    const init = () => {
      request.get("/work_ai", "/user/image/tags/list").then((res) => {
        res.result.forEach((item, index) => {
          item.tags.unshift({
            name: "全部",
            id: index + "-" + 0,
            checked: true,
          });
        });
        state.tagList = res.result;
        if (route.query.id) {
          // state.tagId[0] = Number(route.query.id);
          state.tagList.map((v, i) => {
            v.tags.map((item) => {
              if (item.id == Number(route.query.id)) {
                state.tagList[i].tags.map((tag) => {
                  tag.checked = false;
                });
                item.checked = true;
              }
            });
          });

          let params = [];
          state.tagList.map((v) => {
            v.tags.map((item) => {
              if (item.checked && typeof item.id == "number") {
                params.push(item.id);
              }
            });
          });
          if (params.length > 0) {
            getCaseList(params.join(","));
          } else {
            getCaseList(undefined);
          }
          return;
        }
        getCaseList(undefined);
      });
    };
    init();

    // 回到顶部
    const backToTop = () => {
      nextTick(() => {
        state.pageRef.scrollTop = 0;
      });
    };

    onMounted(() => {
      state.imageWidth = Math.floor((document.body.clientWidth - 248 - 75) / 6);
    });

    return {
      ...toRefs(state),
      loadImg,
      downloadClick,
      collectClick,
      makeTheSameModelClick,
      sortTextClick,
      tagClick,
      loginCallback,
      Masonry,
      backToTop,
    };
  },
});
</script>

<style lang="less" scoped>
.box {
  width: 100%;
  height: 100%;
  overflow: hidden auto;
  .text-color {
    color: rgba(0, 0, 0, 0.45);
  }

  .ellipsis {
    text-overflow: -o-ellipsis-lastline;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    line-clamp: 3;
    -webkit-box-orient: vertical;
  }
  .title {
    font-size: 14px;
    color: #333333;
    font-weight: bold;
    margin-right: 23px;
  }
  .pointer {
    cursor: pointer;
    margin-bottom: 10px;
  }
  .sort-title {
    font-size: 14px;
    color: #333333;
    font-weight: bold;
    cursor: pointer;
  }
  .breadcrumb {
    margin-bottom: 15px;
  }
  .classify {
    margin-bottom: 5px;

    .classify-tag {
      padding: 6px 15px;
      border-radius: 5px;
      margin-right: 5px;
      cursor: pointer;
    }
    .tag-bg {
      background: #f3f0fe;
      color: #9075f4;
    }
  }
  .classify-title {
    margin-top: 6px;
  }
  .classify-list {
    margin-top: 36px;
    .list {
      cursor: pointer;
      width: 300px;
      height: 200px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 8px;
      margin-right: 16px;
      margin-bottom: 34px;
      position: relative;
      .image {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 160px;
        border-top-right-radius: 9px;
        border-top-left-radius: 9px;
      }
      .main_image {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 158px;
        background-position: center;
        background-repeat: no-repeat;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        background-size: cover;
        border-top-right-radius: 9px;
        border-top-left-radius: 9px;
      }
      .bottom-text {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 43px;
        line-height: 43px;
        padding: 0 20px;
        background: #fff;
        border-bottom-right-radius: 8px;
        border-bottom-left-radius: 8px;
        overflow: hidden; //超出隐藏
        white-space: nowrap; //不换行，同一行展示
        text-overflow: ellipsis; //设置超出部分以省略号展示
      }
      .mask {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 78%;
        text-align: center;
        padding-top: 120px;
        border-top-right-radius: 8px;
        border-top-left-radius: 8px;
        background-color: #00000073;
        opacity: 0.4;
        display: none;
      }
      .sameModel {
        background: linear-gradient(90deg, #938bff, #daaefe);
        border-radius: 3px;
        border: none;
        margin-top: 50px;
        display: none;
      }
      .mask-right {
        position: absolute;
        top: 30px;
        right: 20px;
        display: none;
        .icon-bg {
          width: 25px;
          height: 25px;
          text-align: center;
          line-height: 25px;
          background-color: #00000073;
          opacity: 0.8;
          border-radius: 50%;
          margin-bottom: 10px;
          color: #fff;
          background-image: linear-gradient(to bottom right, #938bff, #daaefe);
        }
      }
    }
  }
  .classify-list :hover {
    .mask {
      display: block;
    }
    .sameModel {
      display: block;
    }
    .mask-right {
      display: block;
    }
  }

  .noData {
    display: flex;
    align-items: center;
    flex-direction: column;
    margin-top: 50px;
  }

  .discoveImg {
    margin-right: 15px;
    margin-bottom: 15px;
    border-radius: 15px;
    position: relative;
    // width: 16.65%;
    .discoveTxt {
      width: 90%;
      height: 95%;
      position: absolute;
      cursor: pointer;

      .bottom-text {
        position: absolute;
        right: 0;
        width: 100%;
        // padding-right: 10px;
        display: flex;
        justify-content: flex-end;
      }
      .mask-right {
        position: absolute;
        right: 10px;
        bottom: 30px;
        width: 80px;
        height: 28px;
        background: rgba(0, 0, 0, 0.1);
        border-radius: 24px;
        backdrop-filter: blur(4px);
        display: flex;
        justify-content: space-around;
        align-items: center;

        .icon-bg {
          width: 25px;
          height: 25px;
          text-align: center;
          line-height: 25px;
          // background-color: #00000073;
          opacity: 0.8;
          border-radius: 50%;
          // margin-bottom: 10px;
          color: #fff;
          font-size: 16px;
          // background-image: linear-gradient(to bottom right, #938bff, #daaefe);
        }
        display: none;
      }

      .text-box {
        width: 90%;
        color: #cbd5e1;
        position: absolute;
        bottom: 80px;
        left: 5%;
        flex-direction: column;
        background: #0f121c;
        box-shadow: 0 4px 14px 0 rgba(0, 0, 0, 0.5);
        border-radius: 8px;
        padding: 10px 12px 15px 12px;
        box-sizing: border-box;
        z-index: 2;
        display: none;
      }
      .make-box {
        color: #fff;
        padding: 8px 15px;
        position: absolute;
        top: 12px;
        right: 12px;
        background: #f1314e;
        border-radius: 50px;
        box-sizing: border-box;
        z-index: 2;
        display: none;
      }
    }

    img {
      border-radius: 12px;
      width: 100% !important;
      cursor: pointer;
      object-fit: cover;
    }
  }
  .discoveImg > .discoveTxt:hover {
    width: 100%;
    position: absolute;
    cursor: pointer;
    // display: block;

    .text-box {
      display: block;
      min-height: auto;
      max-height: 81px;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 3;
      line-clamp: 3;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
    .make-box {
      display: block;
    }

    .bottom-text {
      position: absolute;
      right: 0;
      width: 100%;
      // padding-right: 10px;
      display: flex;
      justify-content: flex-end;
      display: block;
    }
    .mask-right {
      position: absolute;
      right: 10px;
      bottom: 0px;
      width: 80px;
      height: 28px;
      background: rgba(0, 0, 0, 0.1);
      border-radius: 24px;
      backdrop-filter: blur(4px);
      display: flex;
      justify-content: space-around;
      align-items: center;

      .icon-bg {
        width: 25px;
        height: 25px;
        text-align: center;
        line-height: 25px;
        // background-color: #00000073;
        opacity: 0.8;
        border-radius: 50%;
        // margin-bottom: 10px;
        color: #fff;
        font-size: 16px;
        // background-image: linear-gradient(to bottom right, #938bff, #daaefe);
      }
    }
  }
  .back-to-top {
    position: fixed;
    bottom: 20px;
    right: 2px;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    border: 2px solid #000;
    z-index: 99;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 10px;
    cursor: pointer;
    font-size: 20px;
    font-weight: 800;
  }
}
</style>
